package com.batchengine.db.handlers;

import com.batchengine.db.ResultSetHandler;
import com.batchengine.db.RowProcessor;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <code>ResultSetHandler</code> implementation that converts the first
 * <code>ResultSet</code> row into a JavaBean. This class is thread safe.
 *
 * @see com.batchengine.db.ResultSetHandler
 */
public class BeanHandler implements ResultSetHandler {

    /**
     * The Class of beans produced by this handler.
     */
    private Class type = null;

    /**
     * The RowProcessor implementation to use when converting rows
     * into beans.
     */
    private RowProcessor convert = ArrayHandler.ROW_PROCESSOR;

    /**
     * Creates a new instance of BeanHandler.
     *
     * @param type The Class that objects returned from <code>handle()</code>
     *             are created from.
     */
    public BeanHandler(Class type) {
        this.type = type;
    }

    /**
     * Creates a new instance of BeanHandler.
     *
     * @param type    The Class that objects returned from <code>handle()</code>
     *                are created from.
     * @param convert The <code>RowProcessor</code> implementation
     *                to use when converting rows into beans.
     */
    public BeanHandler(Class type, RowProcessor convert) {
        this.type = type;
        this.convert = convert;
    }

    /**
     * Convert the first row of the <code>ResultSet</code> into a bean with the
     * <code>Class</code> given in the constructor.
     *
     * @return An initialized JavaBean or <code>null</code> if there were no
     *         rows in the <code>ResultSet</code>.
     * @throws SQLException if a database access error occurs
     * @see com.batchengine.db.ResultSetHandler#handle(java.sql.ResultSet)
     */
    public Object handle(ResultSet rs) throws SQLException {
        return rs.next() ? this.convert.toBean(rs, this.type) : null;
    }

}
